<template>
  <div class="mobile-login">
    <!-- 开发模式提示 -->
    <div v-if="isDev && !isMobileDevice" class="dev-tip">
      <van-notice-bar
        text="开发模式：PC端访问移动端页面，建议使用浏览器开发者工具模拟移动设备"
        color="#1989fa"
        background="#ecf9ff"
      />
    </div>

    <!-- 顶部标题 -->
    <van-nav-bar title="用户登录" />

    <!-- 登录表单 -->
    <div class="login-container">
      <div class="logo-section">
        <van-image
          width="80"
          height="80"
          src="/logo.png"
          round
        />
        <h2 class="app-title">{{ title }}</h2>
      </div>

      <van-form @submit="handleLogin" class="login-form">
        <div class="form-fields">
          <!-- 用户名输入框 -->
          <van-field
            v-model="loginForm.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
            left-icon="user-o"
          />

          <!-- 密码输入框 -->
          <van-field
            v-model="loginForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
            left-icon="lock"
          />

          <!-- 验证码输入框 -->
          <van-field
            v-if="captchaEnabled"
            v-model="loginForm.code"
            name="code"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]"
            left-icon="shield-o"
          >
            <template #button>
              <van-image
                :src="codeUrl"
                width="80"
                height="32"
                @click="getCode"
                style="cursor: pointer; border-radius: 6px; border: 1px solid #eee;"
              />
            </template>
          </van-field>
        </div>

        <!-- 记住密码选项 -->
        <div class="remember-row">
          <van-checkbox v-model="loginForm.rememberMe">记住密码</van-checkbox>
        </div>

        <!-- 登录按钮 -->
        <div class="login-button">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            size="large"
          >
            {{ loading ? '登录中...' : '登录' }}
          </van-button>
        </div>

        <!-- 注册链接 -->
        <div class="register-link">
          <span>还没有账号？</span>
          <van-button
            type="default"
            size="small"
            plain
            @click="goToRegister"
          >
            立即注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast, showFailToast } from 'vant'
import { login, getCodeImg } from '@/api/login'
import useUserStore from '@/store/modules/user'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

// 获取应用标题
const title = import.meta.env.VITE_APP_TITLE

// 开发环境和设备检测
const isDev = import.meta.env.DEV
const isMobileDevice = /Android|webOS|iPhone|iPod|BlackBerry|iPad|Windows Phone|Mobile/i.test(navigator.userAgent)

// 路由和状态管理
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loginForm = reactive({
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
})

const loading = ref(false)
const captchaEnabled = ref(true)
const codeUrl = ref('')

// 监听路由变化，获取重定向地址
const redirect = ref(undefined)
watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

// 登录处理函数
async function handleLogin() {
  try {
    loading.value = true
    
    // 处理记住密码
    if (loginForm.rememberMe) {
      Cookies.set('username', loginForm.username, { expires: 30 })
      Cookies.set('password', encrypt(loginForm.password), { expires: 30 })
      Cookies.set('rememberMe', loginForm.rememberMe, { expires: 30 })
    } else {
      Cookies.remove('username')
      Cookies.remove('password')
      Cookies.remove('rememberMe')
    }
    
    // 调用 store 的登录方法
    await userStore.login(loginForm)
    
    // 登录成功提示
    showSuccessToast('登录成功')
    
    // 跳转到目标页面或移动端首页
    const query = route.query
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur]
      }
      return acc
    }, {})
    
    // 移动端登录成功后跳转到移动端首页
    router.push({ 
      path: redirect.value || '/mobile-dashboard', 
      query: otherQueryParams 
    })
    
  } catch (error) {
    console.error('登录失败:', error)
    showFailToast('登录失败，请检查用户名和密码')
    
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode()
    }
  } finally {
    loading.value = false
  }
}

// 获取验证码
async function getCode() {
  try {
    const res = await getCodeImg()
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.uuid = res.uuid
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    showFailToast('获取验证码失败')
  }
}

// 跳转到注册页面
function goToRegister() {
  router.push('/mobile-register')
}

// 从 Cookie 获取保存的用户信息
function getCookie() {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  
  if (username && password && rememberMe) {
    loginForm.username = username
    loginForm.password = decrypt(password)
    loginForm.rememberMe = Boolean(rememberMe)
  }
}

// 组件挂载时执行
onMounted(() => {
  getCode()
  getCookie()
})
</script>

<style scoped>
.mobile-login {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.login-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 24px 0 24px 0;
}

.logo-section {
  text-align: center;
  margin-bottom: 28px;
}

.app-title {
  margin-top: 14px;
  color: white;
  font-size: 26px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.login-form {
  background: white;
  border-radius: 20px;
  padding: 28px 18px 20px 18px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.13);
  margin: 0 18px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.form-fields {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.remember-row {
  display: flex;
  align-items: center;
  margin: 10px 0 0 2px;
}

.login-button {
  margin: 28px 0 10px 0;
}

.register-link {
  text-align: center;
  margin-top: 8px;
  font-size: 14px;
  color: #888;
}

.register-link .van-button {
  margin-left: 6px;
  vertical-align: middle;
}

.dev-tip {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

:deep(.van-field__label) {
  color: #333;
  font-weight: 500;
  font-size: 15px;
  width: 60px !important;
  flex-shrink: 0;
}

:deep(.van-field__control) {
  color: #333;
  font-size: 16px;
}

:deep(.van-field__placeholder) {
  color: #999;
}

:deep(.van-field) {
  background-color: #f8f9fa;
  border-radius: 12px;
  margin-bottom: 0;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

:deep(.van-field:focus-within) {
  border-color: #667eea;
  background-color: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.van-field__left-icon) {
  color: #667eea;
}

:deep(.van-field__control) {
  background-color: transparent;
}

:deep(.van-field__value) {
  flex: 1;
  min-width: 0;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  height: 46px;
  font-size: 17px;
  font-weight: 600;
  border-radius: 23px;
}

:deep(.van-button--primary:active) {
  transform: scale(0.98);
}

:deep(.van-checkbox__label) {
  color: #666;
  font-size: 14px;
}

:deep(.van-nav-bar) {
  background: transparent;
  color: white;
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .login-container {
    padding: 10px 0 10px 0;
  }
  .login-form {
    padding: 16px 6px 12px 6px;
    margin: 0 4px;
  }
  .app-title {
    font-size: 20px;
  }
}
</style> 